/**
 * Created by PengWei on 2017/11/18.
 */
namespace game {
    import Sound = egret.Sound;
    import SoundChannel = egret.SoundChannel;
    import Tween = egret.Tween;
    export class SoundManager {
        get baseMusicVolumn(): number {
            return this._baseMusicVolumn;
        }

        set baseMusicVolumn(value: number) {
            this._baseMusicVolumn = value;
            if(this._curChannel && this._musicEnabled && this._globalEnabled)
            {
                this.volumn = 0.5 * this._baseMusicVolumn * this._musicEnvironmentalMulti;
            }
        }

        public set volumn(vol)
        {
            try{
                this._curChannel.volume = vol;
            }catch (e) {
                console.log('volumn set error');
            }
        }

        public get volumn():number{
            try{
                return this._curChannel.volume;
            }catch (e) {
                console.log('volumn get error');
            }
        }



        set musicEnvironmentMulti(value:number){
            this._musicEnvironmentalMulti = value;
            if(this._curChannel && this._musicEnabled && this._globalEnabled)
            {
                this.volumn = 0.5 * this._baseMusicVolumn * this._musicEnvironmentalMulti;
            }
        }

        get baseSoundVolumn(): number {
            return this._baseSoundVolumn;
        }

        set baseSoundVolumn(value: number) {
            this._baseSoundVolumn = value;
        }
        get soundEnabled(): boolean {
            return this._soundEnabled;
        }

        set soundEnabled(value: boolean) {
            this._soundEnabled = value;
            // if (!value)
            //     ServerSetting.writeKey(SettingKey.Sound);
            // else
            //     ServerSetting.removeKey(SettingKey.Sound);
        }

        get musicEnabled(): boolean {
            return this._musicEnabled;
        }

        set globalEnabled(value:boolean){
            this._globalEnabled = value;
            if(!value && this._curChannel){
                Tween.removeTweens(this._curChannel);
                this.volumn = 0;
            }else if(value && this._musicEnabled && this._curChannel){
                this.volumn = 0.5 * this._baseMusicVolumn;
            }
        }

        set musicEnabled(value: boolean) {
            this._musicEnabled = value;
            if (!value && this._curChannel) {
                Tween.removeTweens(this._curChannel);
                this.volumn = 0;
            } else if (value && this._curChannel) {
                this.volumn = 0.5 * this._baseMusicVolumn * this._musicEnvironmentalMulti;
            }

            // if (!value)
            //     ServerSetting.writeKey(SettingKey.Music);
            // else
            //     ServerSetting.removeKey(SettingKey.Music);
        }

        public stopAll()
        {
            this.soundEnabled = false;
            this.musicEnabled = false;
            try{
                this._curChannel.stop();
            }catch(e)
            {

            }
        }

        private static _instance: SoundManager;

        public static get Instance(): SoundManager {
            if (!this._instance)
                this._instance = new SoundManager();
            return this._instance;
        }

        private _musicEnabled: boolean = true;
        private _soundEnabled: boolean = true;
        private _globalEnabled: boolean = true;
        
        private _baseSoundVolumn:number = 0;
        private _baseMusicVolumn:number = 0;
        private _musicEnvironmentalMulti:number = 1;
        private _soundEnvironmentalMulti:number = 1;

        private _curChannel: SoundChannel;
        private _curBgmName: string;
        private _curSound:string;
        private _isGlobalSwitchOn:boolean = false;

        private _soundCfg:Map<string,number>;
        private _cacheFirstBgm:any;

        public constructor() {
            this._soundCfg = new Map<string,number>();
            this.init();
            document.addEventListener("visibilitychange",()=>{
                this.webStateChange(this);
            });
            document.addEventListener("webkitvisibilitychange", ()=>{
                this.webStateChange(this);
            });
            document.addEventListener("msvisibilitychange", ()=>{
                this.webStateChange(this);
            });
        }

        public webStateChange(thisObj:SoundManager)
        {
            if(document.hidden || document["webkitHidden"] || document["msHidden"]){
                thisObj.globalEnabled = false;
            }else{
                thisObj.globalEnabled = true;
            }
        }

        public set cacheFirstBgm(bgm:any)
        {
            this._cacheFirstBgm = bgm;
        }

        public get cacheFirstBgm()
        {
            return this._cacheFirstBgm;
        }

        // public playBgmByHour() {
        //     let hour = WorldClock.Instance.hour;
        //     let bgm;
        //     if (hour < 6)
        //         bgm = "night";
        //     else if (hour < 12)
        //         bgm = "morning";
        //     else if (hour < 18)
        //         bgm = "day";
        //     else if (hour < 22)
        //         bgm = "dawn";
        //     else
        //         bgm = "night";
        //
        //     this.playBgm(bgm);
        // }

        // public playBgmInInstance() {
        //     let bgm = Math.floor(Math.random() * 15) + 1;
        //     this.playBgm(bgm.toString());
        // }

        public tryPlayBgm()
        {
            if(!this._isGlobalSwitchOn)
            {
                if(this._curBgmName)
                {
                    let key = ResourceManager.getShortSound(this._curBgmName);
                    if(RES.getRes(key))
                    {
                        this._isGlobalSwitchOn = true;
                        this.musicLoaded(RES.getRes(key),key);
                    }
                }else{
                    RES.getResAsync(ResourceManager.getShortSound(this._curBgmName),this.musicLoaded,this);
                }
            }
        }

        public get curBgmName():string{
            return this._curBgmName;
        }

        public playBgm(name: string,force:boolean = false) {
            if (this._curBgmName == name && !force)return;
            this._curBgmName = name;
            if (this._curChannel)
            {
                let channel:SoundChannel = this._curChannel;
                channel.stop();
                // Tween.get(channel).to({volume: 0}, 1000).call(channel.stop,channel);
            }
            let key = ResourceManager.getShortSound(this._curBgmName);
            if(RES.getRes(key))
                this.musicLoaded(RES.getRes(key),key);
            else
                RES.getResAsync(key,this.musicLoaded,this);
        }

        private onTouchTap()
        {
            // GameParams.stage.removeEventListener(egret.TouchEvent.TOUCH_TAP,this.onTouchTap,this);
            this._isGlobalSwitchOn = true;
            if (this.curBgmName)
                this.playBgm(this.curBgmName,true);
            else
                this.playBgm('city',true);
        }

        public tryFirstPlay()
        {
            // if(!this._isGlobalSwitchOn)
                // GameParams.stage.addEventListener(egret.TouchEvent.TOUCH_TAP,this.onTouchTap,this,false,99999);
        }

        private musicLoaded(data,key) {
            if(!this._isGlobalSwitchOn || !data)
            {
                this._curBgmName = null;
                return;
            }

            if(key != ResourceManager.getShortSound(this._curBgmName))return;

            let sound:Sound = data;
            this._curChannel = sound.play(0,0);
            let targetVolumn = (this._musicEnabled && this._globalEnabled)?0.5 * this._baseMusicVolumn * this._musicEnvironmentalMulti:0;
            if(this._curBgmName == "battle")targetVolumn *= 0.7;
            this.volumn = targetVolumn;
        }

        public playSound(name: string, volumn: number = 1) {
            if((!this._soundEnabled) || (!this._globalEnabled))return;
            // if(name == "button")return;//2018/4/1优化内容取消这个音效
            let key = ResourceManager.getShortSound(name);
            volumn = Math.min(volumn,1);
            this._soundCfg.set(key,volumn);
            if(!this._isGlobalSwitchOn)            {
                if(!RES.getRes(key))
                {
                    RES.getResAsync(key,this.loadSoundComplete,this);
                    return;
                }
            }

            this._curSound = name;
            RES.getResAsync(ResourceManager.getShortSound(name),this.loadSoundComplete,this);
        }

        private loadSoundComplete(data,key){
            // if(!this._isGlobalSwitchOn)return;
            let sound:Sound = data;
            if(sound){
                try{
                    let channel = sound.play(0,1);
                    if(channel)
                        channel.volume = this._soundCfg.get(key) * this._baseSoundVolumn;
                }catch(e)
                {
                    //TODO 上传GA
                }
            }
        }

        public init() {
            let localMusicEnabled = egret.localStorage.getItem("m_e");
            if(localMusicEnabled == "0")this._musicEnabled = false;
            else this._musicEnabled = true;
            
            let localMusicVolumn = egret.localStorage.getItem("m_v");
            let floatNum = parseFloat(localMusicVolumn);
            if(localMusicVolumn && floatNum>0 && floatNum<1)this._baseMusicVolumn = floatNum;
            else  this._baseMusicVolumn = 0.2;

            let localSoundEnabled = egret.localStorage.getItem("s_e");
            if(localSoundEnabled == "0")this._soundEnabled = false;
            else this._soundEnabled = true;

            let localSoundVolumn = egret.localStorage.getItem("s_v");
            floatNum = parseFloat(localSoundVolumn);
            if(localSoundVolumn && floatNum>0 && floatNum<1)this._baseSoundVolumn = floatNum;
            else  this._baseSoundVolumn = 0.2;
        }

        public saveConfigToLocal()
        {
            egret.localStorage.setItem("m_e", this._musicEnabled?"1":"0");
            egret.localStorage.setItem("m_v", this._baseMusicVolumn.toString());
            egret.localStorage.setItem("s_e", this._soundEnabled?"1":"0");
            egret.localStorage.setItem("s_v", this._baseSoundVolumn.toString());
        }

    }
}